package com.jy.api.service.impl;

import com.aliyuncs.exceptions.ClientException;
import com.jy.api.domain.SMSType;
import com.jy.api.service.VerificationCodeService;
import com.jy.api.util.AliyunSMSUtil;
import com.jy.api.util.Contens;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {


    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    AliyunSMSUtil aliyunSMSUtil;


    /**
     * 验证码生产
     *
     * @param mobile
     * @return
     */
    public String setCode(String mobile, SMSType type) throws ClientException {
        Random ne = new Random();//实例化一个random的对象ne
        Integer code = ne.nextInt(9999 - 1000 + 1) + 1000;//为变量赋随机值1000-9999
        String key = Contens.SMS_KEY.replace("MOBILE", mobile).replace("TYPE", type.toString());
        String msg = aliyunSMSUtil.sendSMS(mobile, code.toString());
        if (StringUtils.isBlank(msg)) {
            stringRedisTemplate.opsForValue().set(key, code.toString(),
                    5, TimeUnit.MINUTES);
        }
        return msg;
    }
}
